import os
import subprocess
from Config.GetLogger import Logger
"""

"""


def start_Appium_server():
    os.system(r"start /b appium -a 127.0.0.1 -p 4723")  # todo： start /b  appium server挂载到后台

def send_cmd(cmd, encoding='utf-8'):
    '''
    cmd发送命令
    :param cmd:命令
    :param encoding: 编码方式，默认utf-8,出现乱码用gbk
    :return:
    '''
    res = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, encoding=encoding)
    com = res.communicate()
    value = com[0]
    res.terminate()
    return value

def kill_appium_server(port):
    try:
        # 查找对应端口的pid
        cmd_find = 'netstat -aon | findstr %s' % port
        text = send_cmd(cmd_find, encoding="gbk")
        if text != '':
            res = text.split("\n")
            for i in res:
                if "LISTENING" in i:
                    pid = (i.split()[-1]).strip()
                    # 执行被占用端口的pid
                    cmd = 'taskkill /f /pid %s' % pid
                    res = send_cmd(cmd, encoding="gbk")
                    logs = Logger().log('appium server')
                    logs.debug(str(res).strip())
                    if ("成功" in res) or ("SUCCESS".lower() in res.lower()):
                        logs.debug("port %s appium server close" %str(port))
        else:
            return
    except:
        return

